package com.example.deepseek.utils;

import org.springframework.stereotype.Component;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class MessageFormatterHelper {

    /**
     * 格式化消息内容，支持Markdown语法
     * @param content 原始消息内容
     * @return 格式化后的HTML内容
     */
    public String format(String content) {
        if (content == null || content.isEmpty()) {
            return "";
        }

        // 首先处理代码块 - 这必须在其他处理之前完成，避免内部内容被修改
        content = formatCodeBlocks(content);

        // 处理其他Markdown元素
        content = formatMarkdown(content);

        return content;
    }

    /**
     * 处理代码块
     */
    private String formatCodeBlocks(String content) {
        // 匹配 ```language code ``` 格式的代码块
        Pattern codeBlockPattern = Pattern.compile("```(\\w*)\\s*([\\s\\S]*?)```", Pattern.MULTILINE);
        Matcher codeBlockMatcher = codeBlockPattern.matcher(content);

        StringBuffer sb = new StringBuffer();
        while (codeBlockMatcher.find()) {
            String language = codeBlockMatcher.group(1).trim();
            String code = codeBlockMatcher.group(2).trim();

            // 转义HTML特殊字符
            code = escapeHtml(code);

            String replacement = "<pre><code class=\"language-" + language + "\">" + code + "</code></pre>";
            codeBlockMatcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
        }
        codeBlockMatcher.appendTail(sb);

        return sb.toString();
    }

    /**
     * 处理Markdown文本
     */
    private String formatMarkdown(String content) {
        // 处理行内代码
        content = content.replaceAll("`([^`]+)`", "<code>$1</code>");

        // 处理标题
        content = content.replaceAll("(?m)^# (.+)$", "<h1>$1</h1>");
        content = content.replaceAll("(?m)^## (.+)$", "<h2>$1</h2>");
        content = content.replaceAll("(?m)^### (.+)$", "<h3>$1</h3>");
        content = content.replaceAll("(?m)^#### (.+)$", "<h4>$1</h4>");
        content = content.replaceAll("(?m)^##### (.+)$", "<h5>$1</h5>");
        content = content.replaceAll("(?m)^###### (.+)$", "<h6>$1</h6>");

        // 处理粗体和斜体
        content = content.replaceAll("\\*\\*([^*]+?)\\*\\*", "<strong>$1</strong>");
        content = content.replaceAll("\\*([^*]+?)\\*", "<em>$1</em>");

        // 处理超链接
        content = content.replaceAll("\\[([^\\]]+)\\]\\(([^)]+)\\)", "<a href=\"$2\" target=\"_blank\">$1</a>");

        // 处理无序列表
        Pattern ulPattern = Pattern.compile("(?m)^- (.+)$");
        Matcher ulMatcher = ulPattern.matcher(content);
        content = ulMatcher.replaceAll("<li>$1</li>");
        // 将连续的<li>标签包装在<ul>中
        content = wrapConsecutiveTags(content, "<li>", "</li>", "<ul>", "</ul>");

        // 处理有序列表
        Pattern olPattern = Pattern.compile("(?m)^\\d+\\. (.+)$");
        Matcher olMatcher = olPattern.matcher(content);
        content = olMatcher.replaceAll("<li>$1</li>");
        // 将连续的<li>标签包装在<ol>中
        content = wrapConsecutiveTags(content, "<li>", "</li>", "<ol>", "</ol>");

        // 处理引用
        Pattern quotePattern = Pattern.compile("(?m)^> (.+)$");
        Matcher quoteMatcher = quotePattern.matcher(content);
        content = quoteMatcher.replaceAll("<blockquote>$1</blockquote>");
        // 合并连续的引用块
        content = content.replaceAll("</blockquote>\\s*<blockquote>", "<br>");

        // 处理水平分割线
        content = content.replaceAll("(?m)^---+$", "<hr>");

        // 处理表格 (简单表格，不支持对齐等高级特性)
        // 这部分需要更复杂的正则表达式，此处略过

        // 处理换行 (在最后处理，避免影响其他标记)
        content = content.replaceAll("\\n", "<br>");

        return content;
    }

    /**
     * 将连续的标签包装在父标签中
     */
    private String wrapConsecutiveTags(String content, String startTag, String endTag, String parentStartTag, String parentEndTag) {
        StringBuilder result = new StringBuilder();
        boolean inBlock = false;

        String[] lines = content.split("<br>|\\n");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];

            if (line.startsWith(startTag) && line.endsWith(endTag)) {
                if (!inBlock) {
                    result.append(parentStartTag);
                    inBlock = true;
                }
                result.append(line);
            } else {
                if (inBlock) {
                    result.append(parentEndTag);
                    inBlock = false;
                }
                result.append(line);
            }

            if (i < lines.length - 1) {
                result.append("<br>");
            }
        }

        if (inBlock) {
            result.append(parentEndTag);
        }

        return result.toString();
    }

    /**
     * 转义HTML特殊字符
     */
    private String escapeHtml(String text) {
        return text.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#039;");
    }
}